package com.ferry.jraft.model;

import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * @Author ferry
 * @create 2022/5/17 15:08
 * @description 日志条目
 */

@Builder
@Getter
@Setter
public class LogEntry implements Serializable, Comparable {

    private static final long serialVersionUID = 7819372950910446124L;

    private Long index;

    private long term;

    public LogEntry(Long index, long term, String value) {
        this.index = index;
        this.term = term;
        this.value = value;
    }

    /**
     * 操作的内容
     */
    private String value;


    /**
     * 原论文中提到两个条目需要比较哪一条更新：
     * ● 如果两份日志最后一个条目的任期号不同，则任期号更大的更新
     * ● 如果两份日志最后一个条目的任期号相同，则索引更大的更新
     *
     * @param o
     * @return
     */
    @Override
    public int compareTo(Object o) {
        if (o == null) {
            return -1;
        }
        LogEntry log = (LogEntry) o;

        if (this.getTerm() != log.getTerm()) {
            return (int) (this.getTerm() - log.getTerm());
        }
        return (int) (this.getIndex() - log.getIndex());
    }

    @Override
    public String toString() {
        return "LogEntry{" +
                "index=" + index +
                ", term=" + term +
                ", value='" + value + '\'' +
                '}';
    }
}
